package com.example.gallery;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;

import com.example.board.R;


public class ListActivity extends Activity{
	final String TAG = "ListActivity";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		/*super.onCreate(savedInstanceState);
		setContentView(R.layout.simple_spinner_item);*/
		setContentView(R.layout.albumlist);
		getImagePath();
		getImageFile();
		
	}

	@Override
	protected void onResume() {
//		super.onResume();
	
		
	}
	
	
	/*
	 directory를 키로 하는 directory별 이미지 리스트
	 images.keySet()으로 set 뽑으면 됨
	*/
	public void getImagePath(){
		Map<String, List<String>> images = new TreeMap<String, List<String>>();

		String[] projection = { MediaStore.Images.Media.DATA };
		
		Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
		
		if(cursor != null){
		    cursor.moveToLast();
		    int length = cursor.getCount();
		    cursor.moveToFirst();

		    // 길이 안구하고 cursor.is* 로 확인하면서 반복하셔도 됩니다
		    for(int i = 0; i < length; ++i){
		        String data = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA)); 

		        // '/파일명.확장자' 를 잘라내고 경로만
		        String key = data.replaceFirst("/.[^/]+$", "");

		        List<String> dir = images.get(key);
		        if(dir == null){
		            dir = new ArrayList<String>();
		            images.put(key, dir);
		        }
		        dir.add(data);
		                
		        cursor.moveToNext();
		    }
		}
		
	}
	public void getImageFile(){
		File path = new File("/storage/emulate/0/Pictures/Board");
		if(path.isDirectory()){
			File[] files = path.listFiles(new FilenameFilter() {
				
				@Override
				public boolean accept(File dir, String filename) {
					File file = new File(dir, filename);
					if(file.isFile() && !file.isHidden() && filename.matches("^.*\\.(?i)(jpg|png|bmp|gif)$")){
						return true;
					}
					return false;
				}
			});
//			반환받은 files 배열로 작업
			Log.i(TAG, "images....... "+files.toString());
		}
	}
	
}
